package com.example.mvvm.pokemon.net

import com.atom.module.utils.Logs
import com.example.mvvm.JacksonUtils
import com.moczul.ok2curl.CurlInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory


object NetHelper {

    interface CreateClientListener {
        fun build(builder: OkHttpClient.Builder)
    }

    fun createClient(listener: CreateClientListener): OkHttpClient {
        val client = OkHttpClient.Builder()
        client.addInterceptor(CurlInterceptor { message ->
            Logs.e(
                String.format(
                    "Postman CURL -> \n %s \n",
                    message
                )
            )
        })
        client.addNetworkInterceptor(HttpLoggingInterceptor { message ->
            println(
                String.format(
                    "Network Log -> \n %s \n",
                    message
                )
            );
        }.apply {
            this.setLevel(HttpLoggingInterceptor.Level.BODY)
        })
        listener.build(client)
        return client.build()
    }

    fun defaultClient(vararg interceptor: Interceptor): OkHttpClient {
        return createClient(object : CreateClientListener {
            override fun build(builder: OkHttpClient.Builder) {
                interceptor.forEach {
                    builder.addInterceptor(it)
                }
            }
        })
    }

    fun createRetrofit(url: String, client: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl(url)
            .client(client) // 设置client
            .addConverterFactory(JacksonConverterFactory.create(JacksonUtils.objectMapper))// 设置Json解析器
            .build()
    }
}